import { ref, computed, onMounted, unref, watch, onUnmounted, onBeforeUnmount } from 'vue'
import { useImageCache } from '@/utils/preload-tools'

const observerConfig = {
  root: null,
  rootMargin: '50px',
  threshold: 0,
}

// 监控图片是否显示出来
const observer = new IntersectionObserver((entries) => {
  entries.forEach((entry) => {
    if (entry.isIntersecting) {
      const { target } = entry
      observer.unobserve(target)
      loadImg(target)
    }
  })
}, observerConfig)

// 加载图片
const loadImg = async (img) => {
  if (!img) return
  const { src } = img.dataset
  img.src = await useImageCache(src)
  img.classList.remove('loading')
}

export default (props) => {
  const image = ref()

  const init = () => {
    const img = unref(image)
    img && observer.observe(unref(image))
  }

  const destory = () => {
    const img = unref(image)
    img && observer.unobserve(img)
  }

  watch(
    () => props.src,
    () => {
      loadImg(unref(image))
    }
  )

  onMounted(init)
  onBeforeUnmount(destory)

  return {
    image,
  }
}
